package com.dys.hejiayuncommunity.common.core.controller;

import com.dys.hejiayuncommunity.common.constant.HttpStatus;
import com.dys.hejiayuncommunity.common.core.domain.BaseResponse;
import com.dys.hejiayuncommunity.common.core.page.PageDomain;
import com.dys.hejiayuncommunity.common.core.page.PageResult;
import com.dys.hejiayuncommunity.common.utils.ServletUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * @className: com.dys.hejiayuncommunity.common.core.controller.BaseController
 * @description: 基础控制器类，作为所有Controller的基类，提供一些公共方法
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/12/04 22:10
 */
public class BaseController {
    /**
     * 当前页
     */
    private static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示条数
     */
    private static final String PAGE_SIZE = "pageSize";

    /**
     * 封装分页数据
     *
     * @return 分页数据
     */
    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
        pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
        return pageDomain;
    }

    /**
     * 调用PageHelper的startPage，设置分页参数
     */
    protected void startPage() {
        PageDomain pageDomain = getPageDomain();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
    }

    /**
     * 响应分页数据
     *
     * @param list 等待分页的数据
     * @return 分页之后响应的结果
     */
    protected PageResult getData(List<?> list) {
        PageResult pageResult = new PageResult();
        pageResult.setCode(HttpStatus.SUCCESS);
        pageResult.setMessage("分页查询小区数据成功");
        pageResult.setTotal(new PageInfo<>(list).getTotal());
        pageResult.setRows(list);
        return pageResult;
    }

    /**
     * 响应返回结果
     *
     * @param rows 受影响行数
     * @return 统一响应报文
     */
    protected BaseResponse<?> toAjax(int rows) {
        return rows > 0 ? BaseResponse.success(rows) : BaseResponse.failed("操作失败");
    }
}
